<template>
    <div class="import-guide-wrapper">
        <Button icon="ios-cloud-upload-outline" @click="importGuide" style="margin-right:5px"
            >导入指导书</Button
        >
        <!--导入文件-->
        <Modal
            v-model="importGuideModal"
            :mask-closable="false"
            width="500"
            :closable="false"
            :footer-hide="true"
            title="导入指导书"
        >
            <Form
                ref="formItem"
                :model="importGuideFormValidate"
                :rules="importGuideRuleValidate"
                :label-width="80"
            >
                <FormItem label="导入文件" prop="file">
                    <Upload
                        v-model="importGuideFormValidate.file"
                        :action="upLoadUrl"
                        :before-upload="handleUploadIcon"
                    >
                        <Button icon="ios-cloud-upload-outline" :disabled="loading"
                            >选择文件</Button
                        >
                    </Upload>
                    <div class="uploadTypeWrap">
                        <p style="color:#ff9900">
                            <Icon type="ios-alert-outline" />支持导入类型：doc，docx，md
                        </p>
                        <!-- <p style="color:#ff9900">
                            <Icon type="ios-alert-outline" />文件大小不能超过20M
                        </p> -->
                        <p style="color:#ff9900">
                            <Icon type="ios-alert-outline" />指导书标题不能包含 \ * : ? " < > | ; ,
                            + =等字符，长度为1-64个字符
                        </p>
                        <p style="color:#ff9900">
                            <Icon type="ios-alert-outline" />不支持gif等动图导入
                        </p>
                        <p style="color:#ff9900">
                            <Icon
                                type="ios-alert-outline"
                            />导入的指导书文档中的段落标题必须使用一级标题或二级标题，否则将不会作为指导书章节处理，不属于章节的内容导入时可能会丢失
                        </p>
                        <!--<p style="color:#ff0000"><Icon type='ios-alert-outline'/>请按照模板格式编辑指导书，请不要随意编辑指导书模板格式</p>-->
                    </div>
                    <div v-if="importGuideFormValidate.file">
                        <p>文件名: {{ importGuideFormValidate.file.name }}</p>
                        <p>大小：<span v-text="fileSize"></span></p>
                        <Progress :percent="progress"></Progress>
                        <p>速度：<span v-text="speed"></span></p>
                    </div>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="formBtn('formItem')" :loading="loading"
                        >确定</Button
                    >
                    <Button @click="cancelUpload()" style="margin-left: 8px">取消</Button>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
import encryption from '@/libs/encryption.js';
import { exportGuide } from '@/api/guide.js';
export default {
    name: 'ImportGuide',
    props: ['public'],
    data() {
        const validateUpload = (rule, value, callback) => {
            if (!this.importGuideFormValidate.file) {
                callback(new Error('请选择导入的文件'));
            } else {
                callback();
            }
        };
        return {
            USER_ID: '',
            isRootDesigner: false,
            //导入指导书
            importGuideModal: false,
            importGuideFormValidate: {
                file: null
            },
            importGuideRuleValidate: {
                file: [{ required: true, validator: validateUpload, trigger: 'change' }]
            },
            upLoadUrl: `${this.baseURL}/self-study/guide/expGuide/generateExpGuideByWord?isPublic=${0}`,
            formatArr: ['doc', 'docx', 'md'],
            speed: 0,
            loaded: 0,
            progress: 0,
            fileSize: 0,
            loading: false
        };
    },
    watch: {
        public: {
            handler (val) {
                this.upLoadUrl= `${this.baseURL}/self-study/guide/expGuide/generateExpGuideByWord?isPublic=${val}`
            },
            deep: true,
            immediate: true,
        },
    },
    created() {
        // 获取用户id
        let November = sessionStorage.getItem('November');
        November = JSON.parse(encryption.SelfUseDecrypt(November));
        this.USER_ID = November.userId;
        this.isRootDesinger = November.isRootDesinger;
    },
    methods: {
        //导入指导书
        importGuide() {
            this.importGuideModal = true;
            this.importGuideFormValidate.file = '';
        },
        handleUploadIcon(file) {
            this.speed = 0;
            this.loaded = 0;
            this.progress = 0;
            this.isUpdataing = true;
            this.importGuideFormValidate.file = '';
            this.onlyFileName = file.name + '_' + new Date().getTime();
            if (file) {
                if (file.size > 1024 * 1024) {
                    this.fileSize =
                        (Math.round((file.size * 100) / (1024 * 1024)) / 100).toString() + 'MB';
                } else {
                    this.fileSize = (Math.round((file.size * 100) / 1024) / 100).toString() + 'KB';
                }
                //验证名称
                if (file.name) {
                    let exceededNum = file.name.lastIndexOf('.');
                    let exceededStr = file.name
                        .substring(exceededNum + 1, file.name.length)
                        .trim()
                        .toLowerCase();
                    let fileName = file.name.substring(0, exceededNum);
                    let reg = /[\\\:：*?？"”<>|;；，,+=]/gi;
                    if (exceededStr && this.formatArr.indexOf(exceededStr) == -1) {
                        this.$Message.error({
                            content: '不支持当前文件类型',
                            duration: 3
                        });
                    } else if (reg.test(fileName) || fileName.length > 64) {
                        this.$Message.error({
                            content:
                                '文件名称不能包含 \ * : ? " < > | ; , + =等字符，名称长度为1-64个字符',
                            duration: 3
                        });
                    } 
                    // else if (file.size > 20480000) {
                    //     this.$Message.error({
                    //         content: '文件大小不能超过20M',
                    //         duration: 3
                    //     });
                    // } 
                    else {
                        this.importGuideFormValidate.file = file;
                    }
                    return false;
                }
            }
        },
        formBtn(name) {
            let _this = this;
            if (!this.importGuideFormValidate.file) {
                _this.$Message.warning({
                    content: '请先选择文件！',
                    duration: 2
                });
                return;
            }
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let formData = new window.FormData();
                    formData.append('file', _this.importGuideFormValidate.file);
                    let file = {
                        name: this.onlyFileName //this.formItem.file.name
                    };
                    _this.loading = true;
                    _this
                        .axios({
                            method: 'post',
                            url: _this.upLoadUrl,
                            data: formData,
                            headers: {
                                'Content-type': 'multipart/form-data'
                            },
                            timeout:0,
                            onUploadProgress: (progressEvent) => {
                                //解决导入过程中关闭了modal,再选择文件，会显示上次导入的进度级速度问题
                              console.log('--------progressEvent------------',progressEvent)
                                if (
                                    file.name &&
                                    _this.onlyFileName &&
                                    file.name != _this.onlyFileName
                                ) {
                                    return;
                                }
                                var complete = Math.floor(
                                    (progressEvent.loaded / progressEvent.total) * 100
                                );
                                _this.progress = complete;
                                function getspeed() {
                                    var aaspeed = Number(progressEvent.loaded - _this.loaded);
                                    _this.loaded = progressEvent.loaded;
                                    if (aaspeed > 1024 * 1024) {
                                        _this.speed =
                                            (
                                                Math.round((aaspeed * 100) / (1024 * 1024)) / 100
                                            ).toString() + 'MB/s';
                                    } else {
                                        _this.speed =
                                            (Math.round((aaspeed * 100) / 1024) / 100).toString() +
                                            'KB/s';
                                    }
                                }
                                setInterval(getspeed(), 1000);
                            }
                        })
                        .then((data) => {
                            let res = data.data;
                            if (res.code == 1) {
                                _this.importGuideFormValidate.file = null;
                                if (_this.progress === 100) {
                                    this.$emit(
                                        'on-success',
                                        Object.assign(res.data, {
                                            id: res.data.guidbookid,
                                            name: res.data.guidbookname
                                        })
                                    );
                                    _this.$Message.success({
                                        content: '导入成功！',
                                        duration: 2
                                    });
                                }
                                setTimeout(() => {
                                    _this.loading = false;
                                    this.importGuideModal = false;
                                    this.uploadShow = false;
                                    // this.refreshFile();
                                }, 2000);
                            } else {
                                _this.loading = false;
                                this.importGuideFormValidate.file = null;
                                this.speed = 0;
                                this.loaded = 0;
                                this.fileSize = 0;
                                this.progress = 0;
                                this.uploadShow = false;
                                _this.$Message.error({
                                    content: res.message,
                                    duration: 3
                                });
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                            _this.$Message.error('服务器连接失败！');
                            _this.loading = false;
                        });
                } else {
                    _this.$Message.error('请完善信息！');
                }
            });
        },
        cancelUpload() {
            //关闭导入给出提示
            this.importGuideModal = false;
            //              let _this = this
            //              if(_this.isUpdataing){
            //                  _this.uploadShow = true
            //                  _this.changeModalLoading()
            //              }else{
            //                  this.uploadFileModal = false;
            //              }
        }
    }
};
</script>
<style scoped>
.import-guide-wrapper {
    display: inline-block;
}
</style>
